import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo } from '@/api/user'
// import { reqLogin, reqUserInfo, reqLogout } from '@/api/user' 
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
// import type {
//     loginFormData,
//     loginResponseData,
//     userInfoReponseData,
// } from '@/api/user/type'

import { constantRoute, asnycRoute, anyRoute } from '../../router/routers'
import router from '../../router/index'
import cloneDeep from 'lodash/cloneDeep'

// 用户菜单权限
function filterAsyncRoute(asnycRoute: any, routes: any) {
    return asnycRoute.filter((item: any) => {
        if (routes.includes(item.name)) {
            if (item.children && item.children.length > 0) {
                item.children = filterAsyncRoute(item.children, routes)
            }
            return true
        }
    })
}

const userUserStore = defineStore('user', {
    state: () => {
        return {
            token: GET_TOKEN(), //用户唯一标识token
            menuRoutes: constantRoute, //仓库存储生成菜单需要数组(路由)
            username: '',
            avatar: '',
            //存储当前用户是否包含某一个按钮
            buttons: [],
        }
    },
    actions: {
        async userLogin(data: userInfoApi.loginFormData) {
            //登录请求
            const result: userInfoApi.loginResData = await reqLogin(data)
            if (result.code == 200) {
                this.token = result.data.token as string
                SET_TOKEN(result.data.token as string)
            } else {
                // return Promise.reject(new Error(result.data))
                return Promise.reject(result.data)
            }
        },
        async userInfo() {
            const result: userInfoApi.userInfoResData = await reqUserInfo()

            if (result.code == 200) {
                this.username = result.data.checkUser.username
                this.avatar = result.data.checkUser.avatar
                this.buttons = result.data.checkUser.buttons
                //  菜单展示数据
                let userAsyncRoute = filterAsyncRoute(cloneDeep(asnycRoute), result.data.checkUser.routes)
                this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute];

                // 菜单路由添加
                [...userAsyncRoute, anyRoute].forEach((route: any) => {
                    router.addRoute(route);
                })
                return 'ok';

            } else {
                return Promise.reject(result.data)
            }
        },

        async userLogout() {
            this.username = ''
            this.avatar = ''
            this.token = ''
            REMOVE_TOKEN()
        },
    }
})
export default userUserStore